import React, { useContext, useMemo, useState } from 'react'
import Ctx from '../store/Ctx'
import Myback from '../conponent/Myback'
import { Tabs, ProductCard, Tag, Button, Space } from 'react-vant'
import type { dataTS } from '../store/type'
import type { RouteComponentProps } from 'react-router-dom'


export default function Home(props:RouteComponentProps) {

  //获取数据
  let obj = useContext(Ctx)

  //定义一个状态 //全部=0 推荐=1... 以此类推
  let [index, setIndex] = useState(0)

  //使用缓存属性 筛选出对应的页面
  let newlist = useMemo(() => {
    return obj.datalist.filter((item: dataTS) => {
      if (index == 0) {
        return item
      }
      return item.typeId == index
    })
  }, [obj.datalist, index])

  return (
    <div>
      {/* 导航栏 */}
      <Myback title={'首页'} leftText={false}></Myback>

      {/* 标签页 */}
      <Tabs onChange={(e) => {
        setIndex(e)
      }}>
        {['全部', '推荐', '小说', '儿童'].map(item => (
          <Tabs.TabPane key={item} title={item}></Tabs.TabPane>
        ))}
      </Tabs>

      {/* 商品卡片组件 渲染数据 */}
      <div>
        {
          newlist.map((item: dataTS) => {
            return <ProductCard
            onClick={()=>{
              //跳转到详情页
              props.history.push({
                pathname:'/details',
                state:item.id
              })
            }}
              num={<>
                <Space>
                  <span onClick={(e) => {
                    //阻止事件冒泡
                    e.stopPropagation()
                    obj.dispatch({
                      //收藏状态切换
                      type: 'change_collect',
                      payload: item.id
                    })
                  }}>
                    {item.collect ? '已收藏' : '未收藏'}
                  </span>
                  <Button round size='mini' type={item.sub ? 'warning' : 'default'}
                    onClick={(e) => {
                      //阻止事件冒泡
                      e.stopPropagation()
                      obj.dispatch({
                        //订阅状态切换
                        type: 'change_sub',
                        payload: item.id
                      })
                    }}>
                    {item.sub ? '已经订阅' : '免费订阅'}
                  </Button>
                </Space>
              </>}
              key={item.id}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }
      </div>
    </div>
  )
}
